package com.tpo.jnotes.loader.dropbox;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session;
import com.dropbox.client2.session.WebAuthSession;
import com.tpo.jnotes.base.logging.BLogging;
import com.tpo.jnotes.loader.lib.dialogs.LProgressBar;

public class LDropboxDownloader
{

    private static DropboxAPI< ? > client;

    private static DropboxAPI< ? > getClient()
    {
        if( client == null )
        {
            AccessTokenPair accessKey =
                new AccessTokenPair( LDropboxConstants.ACCESS_TOKEN_PAIR1, LDropboxConstants.ACCESS_TOKEN_PAIR2 );
            AppKeyPair appKey =
                new AppKeyPair( LDropboxConstants.APP_KEY_PAIR1, LDropboxConstants.APP_KEY_PAIR2 );
            WebAuthSession session = new WebAuthSession( appKey, Session.AccessType.APP_FOLDER, accessKey );
            client = new DropboxAPI< WebAuthSession >( session );
        }
        return client;
    }

    public static void downloadFile( String fileName, LProgressBar progressBar ) throws DropboxException,
        IOException
    {
        FileOutputStream downloadStream = new FileOutputStream( new File( fileName ) );
        try
        {
            if( progressBar != null )
                getClient().getFile( fileName, null, downloadStream,
                    new LDropboxProgressListener( progressBar ) );
            else
                getClient().getFile( fileName, null, downloadStream, null );
        }
        catch( DropboxException e )
        {
            BLogging.error( "DropboxDownloader > Error when dowloading new version." );
        }
        finally
        {
            downloadStream.close();
        }
    }

    public static void downloadFile( String fileName ) throws DropboxException, IOException
    {
        downloadFile( fileName, null );
    }

}
